package frontend.pages.worklog.monthly;

import java.io.Serializable;
import java.util.*;

public class DisplayMonthBuilder {

    public static List<DisplayableWeek> getDisplayWeeks(Calendar monthStartDay) {
        List<DisplayableWeek> weeks = new ArrayList<DisplayableWeek>();

        int currentWeekOfMonth = 0;
        DisplayableWeek currentWeek = null;
        Calendar currentDayCalendar = (Calendar) monthStartDay.clone();
        currentDayCalendar.setFirstDayOfWeek(Calendar.MONDAY);

        for (int day = 1; day <= monthStartDay.getActualMaximum(Calendar.DAY_OF_MONTH); day ++) {

            currentDayCalendar.set(Calendar.DAY_OF_MONTH, day);
            int dayOfWeek = currentDayCalendar.get(Calendar.DAY_OF_WEEK);
            int weekOfMonth = currentDayCalendar.get(Calendar.WEEK_OF_MONTH);

            if (weekOfMonth > currentWeekOfMonth) {
                currentWeek = new DisplayableWeek();
                weeks.add(currentWeek);
                currentWeekOfMonth ++;
            }

            currentWeek.set(dayOfWeek, (Calendar) currentDayCalendar.clone());
        }
        return weeks;
    }

    public static class DisplayableWeek implements Serializable {
        private Map<Integer, Calendar> dayOfWeekToDayOfMonthMap = new LinkedHashMap<Integer, Calendar>();

        public DisplayableWeek() {
            dayOfWeekToDayOfMonthMap.put(Calendar.MONDAY, null);
            dayOfWeekToDayOfMonthMap.put(Calendar.TUESDAY, null);
            dayOfWeekToDayOfMonthMap.put(Calendar.WEDNESDAY, null);
            dayOfWeekToDayOfMonthMap.put(Calendar.THURSDAY, null);
            dayOfWeekToDayOfMonthMap.put(Calendar.FRIDAY, null);
            dayOfWeekToDayOfMonthMap.put(Calendar.SATURDAY, null);
            dayOfWeekToDayOfMonthMap.put(Calendar.SUNDAY, null);
        }

        public Map<Integer, Calendar> getDayOfWeekToDayOfMonthMap() {
            return dayOfWeekToDayOfMonthMap;
        }

        public void set(int dayOfWeek, Calendar day) {
            dayOfWeekToDayOfMonthMap.put(dayOfWeek, day);
        }
    }
}
